using Godot;
using System;
using System.Diagnostics;
using Godot.Collections;

/// <summary>
/// 敌人路径
/// </summary>
public partial class EnemyPath : Path3D
{
	[Export] public PackedScene ExEnemyScene;

	/// <summary>
	/// 计时器曲线
	/// </summary>
	[Export] public Node ExDifficultyManager;
	
	
	[Export] public CanvasLayer ExVictoryLayer;

	private DifficultyManager _difficultyManager;
	private VictoryLayer _victoryLayer;
	
	
	private Timer _timer;

	public override void _Ready()
	{
		_timer = (Timer)GetNode("Timer");

		_difficultyManager = ExDifficultyManager as DifficultyManager;
		_victoryLayer = ExVictoryLayer as VictoryLayer;
		// GD.Print(_difficultyManager);
	}

	/// <summary>
	/// 敌人产卵方法
	/// </summary>
	public void spawnEnemy()
	{
		Enemy newEnemy = ExEnemyScene.Instantiate() as Enemy;
		if (newEnemy == null)
		{
			return;
		}

		// 设置新的最大生命值
		newEnemy.MaxHealth = _difficultyManager.GetEnemyHealth();
		AddChild(newEnemy);
		if (_difficultyManager != null)
		{
			_timer.WaitTime = _difficultyManager.GetSpawnTime();
			// GD.Print(_timer.WaitTime);
			GD.Print(newEnemy.CurrentHealth);
			// 将树退出的信号连接到enemyDefeated函数
			newEnemy.TreeExited += enemyDefeated;
		}
	}

	public void _on_timer_timeout()
	{
		spawnEnemy();
	}

	/// <summary>
	/// 游戏结束，停止敌人产卵
	/// </summary>
	public void OnDifficultyManagerStopSpawning()
	{
		GD.Print("进入OnDifficultyManagerStopSpawning");
		_timer.Stop();
	}


	/// <summary>
	/// 敌人都被击败
	/// </summary>
	public void enemyDefeated()
	{
		if (_timer.IsStopped())
		{
			for (int i = 0; i < GetChildren().Count; i++)
			{
				Node node = GetChildren()[i];
				// 如果找到子节点为路径节点，则停止后续代码执行
				if (node is PathFollow3D)
				{
					return;
				}
			}

			_victoryLayer.Victory();
		}
	}
}
